﻿using Microsoft.EntityFrameworkCore.Design;
using ProxyServer.Extensions;

namespace ProxyServer.EntityFrameworkCore;

public abstract class AbstractDesignTimeFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    private string[] _base = [];

    public AbstractDesignTimeFactory()
    {
        _configuration = BuildBaseConfiguration([]).Build();
    }

    public AbstractDesignTimeFactory(string[] args)
    {
        _base = args ?? [];
        _configuration = AbstractDesignTimeFactory.BuildBaseConfiguration(_base).Build();
    }

    public AbstractDesignTimeFactory(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    private IConfiguration _configuration;

    public virtual IConfiguration Configuration => _configuration;

    public virtual IConfiguration BuildConfiguration(string[] args)
    {
        if (args.IsNullOrEmpty() == false)
        {
            return new ConfigurationBuilder().AddConfiguration(_configuration).AddCommandLine(args).Build();
        }
        return _configuration;
    }

    public abstract AppDbContext CreateDbContext(string[] args);

    public static IConfigurationBuilder BuildBaseConfiguration(string[] args)
    {
        var configurationBuilder = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables("PROXY_")
            .AddUserSecrets<AbstractDesignTimeFactory>();

        if (args.IsNullOrEmpty() == false)
        {
            configurationBuilder.AddCommandLine(args);
        }

        return configurationBuilder;
    }
}
